package com.kira.scaffoldmvc.Dubbo.Compression.Strategy;

import com.kira.scaffoldmvc.Dubbo.Compression.Strategy.CompressionStrategy;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
@Slf4j
public class ZipCompression implements CompressionStrategy {
    private static final int COMPRESS_LEVEL = Deflater.DEFAULT_COMPRESSION;

    @Override
    public byte[] compress(String data) {
        byte[] input = data.getBytes(StandardCharsets.UTF_8);
        Deflater deflater = new Deflater(COMPRESS_LEVEL);
        deflater.setInput(input);
        deflater.finish();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length);
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int count = deflater.deflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        deflater.end();
        return outputStream.toByteArray();
    }

    @Override
    public String uncompress(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }
            return outputStream.toString(StandardCharsets.UTF_8.name());
        } catch (DataFormatException | java.io.IOException e) {
            log.error("ZIP解压失败", e);
            throw new RuntimeException("ZIP decompression failed", e);
        } finally {
            inflater.end();
        }
    }
}